#include  <REGX51.h>

void UART_Init()	//初始化,9600bps@11.0592MHz
{
	SCON = 0x50;	//REN=1,允许串口接收,8位数据,可变波特率
	PCON |= 0x80;	//波特率倍速
	TMOD = (TMOD & 0x0F) | 0x20;	//设置定时器模式
	TL1 = 0xFA;	//设置定时器初始值
	TH1 = 0xFA;	//设置定时器重装值
	ET1 = 0;	//禁止定时器中断
	TR1 = 1;	//定时器开始计时
	EA = 1;	    //启用中断
	ES = 1;	    //启用串口中断
}

void Int1_Init()
{
	// 设置INT0
	IT1 = 1;	// 下降沿触发
	EX1 = 1;	// 打开INT1的中断允许
	EA = 1; 	// 打开总中断
}

void UART_Send_Byte(unsigned char date)	//UART发送一个字节
{
	SBUF = date;
	while (!TI);
	TI = 0;
}

void UART_Send_Buf(unsigned char* buf)
{
	while (*buf)
	{
		UART_Send_Byte(*buf);
		++buf;
	}
}

void Delay10us()
{
	unsigned char i;

	i = 25;
	while (--i);
}

unsigned char buf[50] = { 0 };
unsigned int index = 0;

void main()
{	
	UART_Init();
	Int1_Init();
	
	while (1)
	{
		if (index != 0 && buf[index - 1] == '\0')
		{
			P2 = 0;
			UART_Send_Buf(buf);
			index = 0;
		}
	}
}

// 外部中断0的中断函数
void Int1() interrupt 2
{
	Delay10us();
	buf[index] = P0;
	++index;
}

// 串口中断函数
void UART_Routine() interrupt 4
{
	if (RI)
	{
		RI = 0;
	}
}
